package com.xinjian.jianba.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.xinjian.jianba.dao.dwmid.GiftDao;
import com.xinjian.jianba.dao.dwmid.ProductDao;
import com.xinjian.jianba.dao.dwmid.UserAccountDao;
import com.xinjian.jianba.dao.dwmid.UserAccountDetailDao;
import com.xinjian.jianba.dao.dwmid.UserGiftDetailDao;
import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.dao.dwmid.UserPayConfigDao;
import com.xinjian.jianba.dto.CheckCodeDto;
import com.xinjian.jianba.dto.pay.ApplePayDto;
import com.xinjian.jianba.dto.pay.BuyGiftDto;
import com.xinjian.jianba.dto.pay.BuyMeetcoinDto;
import com.xinjian.jianba.dto.pay.GiftVo;
import com.xinjian.jianba.dto.pay.OrderIsPayDto;
import com.xinjian.jianba.dto.pay.PayResultVo;
import com.xinjian.jianba.dto.pay.ProductVo;
import com.xinjian.jianba.dto.pay.SendGiftDto;
import com.xinjian.jianba.dto.pay.SetPayPasswordDto;
import com.xinjian.jianba.dto.pay.UserAccountDetailDto;
import com.xinjian.jianba.dto.pay.UserAccountDetailVo;
import com.xinjian.jianba.dto.pay.UserAccountInfoVo;
import com.xinjian.jianba.dto.pay.UserGiftDetailDto;
import com.xinjian.jianba.dto.pay.UserGiftVo;
import com.xinjian.jianba.dto.pay.WXOrderQueryDto;
import com.xinjian.jianba.dto.pay.weixin.WeiXinPrePay;
import com.xinjian.jianba.enity.GiftEnity;
import com.xinjian.jianba.enity.ProductEnity;
import com.xinjian.jianba.enity.UserAccountDetailEnity;
import com.xinjian.jianba.enity.UserAccountEnity;
import com.xinjian.jianba.enity.UserGiftDetailEnity;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.enity.UserPayConfigEnity;
import com.xinjian.jianba.exception.Page;
import com.xinjian.jianba.exception.Pageable;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.exception.ResponseCodeAwareException;
import com.xinjian.jianba.service.PayService;
import com.xinjian.jianba.service.SmsService;
import com.xinjian.jianba.utils.Constants;
import com.xinjian.jianba.utils.DateUtil;
import com.xinjian.jianba.utils.HttpClientBase;
import com.xinjian.jianba.utils.JianBaEnum;
import com.xinjian.jianba.utils.JianBaEnum.DataStatusEnum;
import com.xinjian.jianba.utils.JianBaEnum.PayStatusEnum;
import com.xinjian.jianba.utils.JianBaEnum.PayTypeEnum;
import com.xinjian.jianba.utils.JianBaEnum.PayWayEnum;
import com.xinjian.jianba.utils.JsonUtil;
import com.xinjian.jianba.utils.MD5Util;
import com.xinjian.jianba.utils.StringUtil;
import com.xinjian.jianba.utils.weixin.OrderNoUtils;
import com.xinjian.jianba.utils.weixin.WeiXinPayUtils;
import com.xinjian.jianba.utils.weixin.WeiXinTradeTypeEnum;
import com.xinjian.jianba.utils.weixin.WeixinTradeStateEnum;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PayServiceImpl implements PayService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PayServiceImpl.class);

    @Value("${weixin.notify.url}")
    private String weixinNotifyUrl;

    @Value("${weixin.prepay.url}")
    private String weixinPrepayUrl;

    @Value("${weixin.app.id}")
    private String weixinAppId;

    @Value("${order.period}")
    private Integer orderPeriod;

    @Value("${weixin.mch.id}")
    private String weixinMchId;

    @Value("${weixin.partner.key}")
    private String weixinPartnerKey;

    @Value("${alipay.gateway.url}")
    private String alipayGatewayUrl;

    @Value("${alipay.notify.url}")
    private String alipayNotifyUrl;

    @Value("${alipay.app.id}")
    private String alipayAppId;

    @Value("${alipay.private.key}")
    private String alipayPrivateKey;

    @Value("${alipay.public.key}")
    private String alipayPublicKey;

    @Value("${alipay.seller.email}")
    private String alipaySellerEmail;

    @Value("${apple.pay.verify.receipt.url}")
    private String applePayVerifyReceiptUrl;

    @Autowired
    private UserAccountDao userAccountDao;

    @Autowired
    private UserPayConfigDao userPayConfigDao;

    @Autowired
    private SmsService smsService;

    @Autowired
    private GiftDao giftDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private UserGiftDetailDao userGiftDetailDao;

    @Autowired
    public UserInfoDao userInfoDao;

    @Autowired
    public UserAccountDetailDao userAccountDetailDao;

    /**
     * 个人账户见币数量
     *
     */
    @Override
    public UserAccountInfoVo userAccountInfo(Long userId) {
        LOGGER.info("PayServiceImpl-------UserAccountInfo------>" + userId);
        UserPayConfigEnity payUserConfig = userPayConfigDao.selectByUserIdOrMobile(userId, null);
        UserAccountEnity userAccountInfo = userAccountDao.selectByUserId(userId);
        UserAccountInfoVo resultVo = new UserAccountInfoVo(userId, 0, 0, BigDecimal.ZERO);
        if (payUserConfig == null) {
            resultVo.setIsHaveSetPassword(0);
        } else {
            resultVo.setIsHaveSetPassword(1);
        }

        if (userAccountInfo == null) {
            return resultVo;
        }
        BeanUtils.copyProperties(userAccountInfo, resultVo);

        return resultVo;
    }

    /**
     * 设置支付密码
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setPassword(SetPayPasswordDto dto) throws Exception {
        // 校验验证码
        CheckCodeDto checkCodeDto = new CheckCodeDto();
        checkCodeDto.setCode(dto.getCheckCode());
        checkCodeDto.setMobile(dto.getMobile());
        checkCodeDto.setType(2);
        smsService.checkCode(checkCodeDto);

        UserPayConfigEnity payUserConfig = userPayConfigDao.selectByUserIdOrMobile(dto.getUserId(), null);
        if (payUserConfig != null) {
            if (StringUtils.isNotBlank(payUserConfig.getMobile())) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "您已经绑定手机!");
            }
        }

        UserPayConfigEnity payMobileConfig = userPayConfigDao.selectByUserIdOrMobile(null, dto.getMobile());
        if (payMobileConfig != null) {
            if (!payMobileConfig.getUserId().equals(dto.getUserId())) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "手机号已经被绑定!");
            }
            if (payMobileConfig.getUserId().equals(dto.getUserId())) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "您已经绑定手机");
            }
        }

        UserPayConfigEnity savEnity = new UserPayConfigEnity();
        savEnity.setUserId(dto.getUserId());
        savEnity.setMobile(dto.getMobile());
        savEnity.setPayPassword(MD5Util.MD5(dto.getPayPassword().trim()));
        savEnity.setCreateTime(new Date());
        savEnity.setUpdateTime(new Date());
        int line = userPayConfigDao.insert(savEnity);
        LOGGER.info("PayServiceImpl-------userPayConfigDao.insert------>" + line);
    }

    /**
     * 修改支付密码
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(SetPayPasswordDto dto) throws Exception {
        // 校验验证码
        CheckCodeDto checkCodeDto = new CheckCodeDto();
        checkCodeDto.setCode(dto.getCheckCode());
        checkCodeDto.setMobile(dto.getMobile());
        checkCodeDto.setType(2);
        smsService.checkCode(checkCodeDto);

        UserPayConfigEnity payConfig = userPayConfigDao.selectByUserIdOrMobile(dto.getUserId(), null);

        if (payConfig == null) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "您还未设置密码!");
        }
        if (!payConfig.getMobile().equals(dto.getMobile())) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "未绑定的手机号!");
        }

        UserPayConfigEnity savEnity = new UserPayConfigEnity();
        savEnity.setUserId(dto.getUserId());
        savEnity.setMobile(dto.getMobile());
        savEnity.setPayPassword(MD5Util.MD5(dto.getPayPassword().trim()));
        savEnity.setUpdateTime(new Date());
        int line = userPayConfigDao.update(savEnity);
        LOGGER.info("PayServiceImpl-------userPayConfigDao.update------>" + line);

    }

    /**
     * 个人礼物收益
     *
     */
    @Override
    public Page<UserGiftVo> userGiftList(UserGiftDetailDto userGiftDetailDto) {
        List<UserGiftDetailEnity> userGiftDetailList = userGiftDetailDao.findPage(userGiftDetailDto);
        Integer count = userGiftDetailDao.findPageCount(userGiftDetailDto);
        List<UserGiftVo> resultList = new ArrayList<UserGiftVo>();
        if (CollectionUtils.isNotEmpty(userGiftDetailList) && userGiftDetailList.size() > 0) {
            // 用户id
            List<Long> userIdList = new ArrayList<Long>();
            // 礼品id
            List<Long> giftIdList = new ArrayList<Long>();
            userGiftDetailList.forEach(gift -> {
                userIdList.add(gift.getSendUserId());
                giftIdList.add(gift.getGiftId());
            });

            // 赠送人信息
            List<UserInfoEnity> userList = this.userInfoDao.findByUserIdList(userIdList);
            Map<Long, UserInfoEnity> userInfoMap = new HashMap<Long, UserInfoEnity>();
            if (!CollectionUtils.isEmpty(userList) && userList.size() > 0) {
                userList.stream().forEach(userInfo -> {
                    userInfoMap.put(userInfo.getId(), userInfo);
                });
            }
            // 礼品信息
            List<GiftEnity> giftList = this.giftDao.selectByIdList(giftIdList);
            Map<Long, GiftEnity> giftInfoMap = new HashMap<Long, GiftEnity>();
            if (!CollectionUtils.isEmpty(giftList) && giftList.size() > 0) {
                giftList.stream().forEach(giftInfo -> {
                    giftInfoMap.put(giftInfo.getId(), giftInfo);
                });
            }
            userGiftDetailList.forEach(userGift -> {
                UserGiftVo vo = new UserGiftVo();
                GiftEnity gift = giftInfoMap.get(userGift.getGiftId());
                vo.setGiftName(gift.getName());
                vo.setGiftIcon(gift.getIcon());

                UserInfoEnity userInfo = userInfoMap.get(userGift.getSendUserId());
                vo.setSendUserName(userInfo.getNickname());
                vo.setSendUserLogo(userInfo.getUserLogo());
                vo.setSendUserId(userGift.getSendUserId());

                vo.setAmount(userGift.getAmount());
                vo.setTime(DateUtil.format(userGift.getCreateTime(), "yyyy.MM.dd HH:mm"));
                resultList.add(vo);
            });

        }
        Pageable pageable = new Pageable(userGiftDetailDto.getPageNumber(), userGiftDetailDto.getPageSize());
        Page<UserGiftVo> pageVo = new Page<UserGiftVo>(resultList, count, pageable);

        return pageVo;
    }

    /**
     * 个人账单详情
     *
     */
    @Override
    public Page<UserAccountDetailVo> userAccountDetail(UserAccountDetailDto userAccountDetailDto) {
        userAccountDetailDto.setStatus(1);
        List<UserAccountDetailEnity> userAccountDetailList = userAccountDetailDao.findPage(userAccountDetailDto);
        Integer count = userAccountDetailDao.findPageCount(userAccountDetailDto);
        List<UserAccountDetailVo> resultList = new ArrayList<UserAccountDetailVo>();
        if (CollectionUtils.isNotEmpty(userAccountDetailList) && userAccountDetailList.size() > 0) {
            userAccountDetailList.forEach(userAccountDetail -> {
                UserAccountDetailVo vo = new UserAccountDetailVo();
                BeanUtils.copyProperties(userAccountDetail, vo);
                vo.setTime(DateUtil.format(userAccountDetail.getCreateTime(), "yyyy.MM.dd HH:mm"));
                resultList.add(vo);
            });
        }
        Pageable pageable = new Pageable(userAccountDetailDto.getPageNumber(), userAccountDetailDto.getPageSize());
        Page<UserAccountDetailVo> pageVo = new Page<UserAccountDetailVo>(resultList, count, pageable);

        return pageVo;
    }

    /**
     * 送礼物： 1、验证账号密码是否正确 2、验证商品是否下架,库存是否足够 3、验证送礼物用户见币数量是否足够 4、减送礼物用户见币数量(乐观锁)
     * 5、减商品库存，加商品的卖出数量(乐观锁) 6、写送礼物用户资金账户流水表 7、写收礼物用户礼品收益流水表
     * 8、更新收礼物用户礼品收益金额(乐观锁)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SendGiftDto sendGift(BuyGiftDto buyGiftDto) throws Exception {
        // 1、验证账号密码是否正确
        UserPayConfigEnity payConfig = userPayConfigDao.selectByUserIdOrMobile(buyGiftDto.getSendUserId(), null);
        if (payConfig == null) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "您还未设置密码!");
        }
        if (!payConfig.getPayPassword().equals(MD5Util.MD5(buyGiftDto.getPayPassword().trim()))) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "密码错误!");
        }
        // 2、验证商品是否下架,库存是否足够
        GiftEnity gift = giftDao.selectById(buyGiftDto.getGiftId());
        if (gift == null) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "商品不存在!");
        }
        if (!gift.getStatus().equals(DataStatusEnum.UP.getValue())) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "商品已经下架或删除!");
        }
        if (gift.getQty().intValue() < 1) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "商品库存不足!");
        }

        // 3、验证户见币数量是否足够
        UserAccountEnity userAccount = userAccountDao.selectByUserId(buyGiftDto.getSendUserId());
        if (userAccount == null) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "请先购买见币!");
        }
        int surplusAmount = userAccount.getTotalAmount() - gift.getAmount();
        if (surplusAmount < 0) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "见币不足!");
        }
        // 4、减用户见币数量(乐观锁)
        UserAccountEnity userUpdAccount = new UserAccountEnity();
        userUpdAccount.setId(userAccount.getId());
        userUpdAccount.setTotalAmount(surplusAmount);
        int expendAmount = (userAccount.getExpendAmount() == null ? 0 : userAccount.getExpendAmount())
                + gift.getAmount();
        userUpdAccount.setExpendAmount(expendAmount);
        userUpdAccount.setValueVersion(userAccount.getValueVersion());
        int userAccountLine = userAccountDao.update(userUpdAccount);
        LOGGER.info("PayServiceImpl-------userAccountDao.update------>" + userAccountLine);
        if (userAccountLine < 1) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新用户见币数量失败!");
        }
        // 5、减商品库存，加商品的卖出数量(乐观锁)
        GiftEnity giftUpd = new GiftEnity();
        giftUpd.setId(gift.getId());
        giftUpd.setQty(gift.getQty() - 1);
        int sellQty = (gift.getSellQty() == null ? 0 : gift.getSellQty()) + 1;
        giftUpd.setSellQty(sellQty);
        giftUpd.setValueVersion(gift.getValueVersion());
        int giftLine = giftDao.update(giftUpd);
        LOGGER.info("PayServiceImpl-------giftDao.update------>" + giftLine);
        if (giftLine < 1) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新礼品数量失败!");
        }
        // 6、写用户资金账户流水表
        UserAccountDetailEnity userAccountDetailEnity = new UserAccountDetailEnity();
        userAccountDetailEnity.setOrderNo(OrderNoUtils.generateUniqueId());
        userAccountDetailEnity.setUserId(buyGiftDto.getSendUserId());
        userAccountDetailEnity.setProductId(buyGiftDto.getGiftId());
        userAccountDetailEnity.setAmount(gift.getAmount());
        userAccountDetailEnity.setTotalAmount(surplusAmount);
        userAccountDetailEnity.setStatus(PayStatusEnum.PAY.getValue());
        userAccountDetailEnity.setPayType(PayTypeEnum.JIAN.getValue());
        userAccountDetailEnity.setCash(BigDecimal.ZERO);
        userAccountDetailEnity.setAmountType(1);
        userAccountDetailEnity.setSourceType(buyGiftDto.getSourceType());
        userAccountDetailEnity.setCreateTime(new Date());
        userAccountDetailEnity.setUpdateTime(new Date());
        int insertAccountDetailLine = userAccountDetailDao.insert(userAccountDetailEnity);
        LOGGER.info("PayServiceImpl-------userAccountDetailDao.insert------>" + insertAccountDetailLine);
        if (insertAccountDetailLine < 1) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户资金账户流水失败!");
        }

        // 7、写礼品收益流水表
        UserGiftDetailEnity giftDetailEnity = new UserGiftDetailEnity();
        giftDetailEnity.setSendUserId(buyGiftDto.getSendUserId());
        giftDetailEnity.setReceiveUserId(buyGiftDto.getReceiveUserId());
        giftDetailEnity.setGiftId(buyGiftDto.getGiftId());
        giftDetailEnity.setAccountDetailNo(userAccountDetailEnity.getId());
        giftDetailEnity.setAmount(gift.getAmount());
        giftDetailEnity.setCreateTime(new Date());
        giftDetailEnity.setUpdateTime(new Date());
        int insertGiftDetailLine = userGiftDetailDao.insert(giftDetailEnity);
        LOGGER.info("PayServiceImpl-------userGiftDetailDao.insert------>" + insertGiftDetailLine);
        if (insertGiftDetailLine < 1) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户礼品收益流水失败!");
        }

        // 8、更新收礼物用户礼品收益金额(乐观锁)
        LOGGER.info("gift.getCash()------>" + gift.getCash());
        UserAccountEnity receiveUser = userAccountDao.selectByUserId(buyGiftDto.getReceiveUserId());
        if (receiveUser == null) {
            UserAccountEnity userSaveAccountEnity = new UserAccountEnity();
            userSaveAccountEnity.setUserId(buyGiftDto.getReceiveUserId());
            userSaveAccountEnity.setTotalAmount(0);
            userSaveAccountEnity.setExpendAmount(0);
            userSaveAccountEnity.setTotalIncome(gift.getCash());
            userSaveAccountEnity.setValueVersion(1L);
            userSaveAccountEnity.setCreateTime(new Date());
            userSaveAccountEnity.setUpdateTime(new Date());
            int userSaveAccountLine = userAccountDao.insert(userSaveAccountEnity);
            LOGGER.info("PayServiceImpl-------userAccountDao.insert------>" + userSaveAccountLine);
            if (userSaveAccountLine < 1) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新用户礼物收益失败!");
            }
        } else {
            UserAccountEnity userReceiveUpdAccount = new UserAccountEnity();
            userReceiveUpdAccount.setId(receiveUser.getId());
            LOGGER.info("receiveUser.getTotalIncome()------>" + receiveUser.getTotalIncome());

            BigDecimal totalIncome = receiveUser.getTotalIncome().add(
                    (gift.getCash() == null ? BigDecimal.ZERO : gift.getCash()));
            userReceiveUpdAccount.setTotalIncome(totalIncome);
            userReceiveUpdAccount.setValueVersion(receiveUser.getValueVersion());
            int userReceiveUpdAccountLine = userAccountDao.update(userReceiveUpdAccount);
            LOGGER.info("PayServiceImpl-------userAccountDao.update------>" + userReceiveUpdAccountLine);
            if (userReceiveUpdAccountLine < 1) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新用户礼物收益失败!");
            }
        }

        SendGiftDto result = new SendGiftDto();
        result.setTotalAmount(surplusAmount);

        return result;
    }

    /**
     * 购买见币 1、根据设备类型，商品id 判断商品是否合法 2、判断商品数量是否足够，扣除商品数量(乐观锁)
     * 3、写用户资金账户表(乐观锁)(ios支付的时候此步骤直接写入到数据库；ALIPAY,WEIXIN的时候在异步通知中写入到数据库)
     * 4、写用户资金账户流水表 5、根据支付类型选择对应的支付方式
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayResultVo buyMeetcoin(BuyMeetcoinDto buyMeetcoinDto) throws Exception {
        PayResultVo resultVo = new PayResultVo();
        // 1、根据设备类型，商品id 判断商品是否合法
        ProductEnity enity = new ProductEnity();
        enity.setStatus(JianBaEnum.DataStatusEnum.UP.getValue());
        enity.setSourceType(buyMeetcoinDto.getSourceType());
        enity.setId(buyMeetcoinDto.getProductId());
        List<ProductEnity> allProductList = productDao.select(enity);
        if (CollectionUtils.isEmpty(allProductList) || allProductList.size() == 0) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "商品已经下架或不存在!");
        }
        ProductEnity productEnity = allProductList.get(0);

        // 2、判断商品数量是否足够，扣除商品数量(乐观锁)
        ProductEnity productUpd = new ProductEnity();
        productUpd.setId(productEnity.getId());
        // 剩余商品数量
        int surplusAmount = (productEnity.getQty() == null ? 0 : productEnity.getQty()) - 1;
        LOGGER.info("PayServiceImpl-------surplusAmount------>" + surplusAmount);
        if (surplusAmount < 0) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "商品数量不足!");
        }
        // 卖出商品数量
        int sellQty = (productEnity.getSellQty() == null ? 0 : productEnity.getSellQty()) + 1;
        LOGGER.info("PayServiceImpl-------sellQty------>" + sellQty);
        productUpd.setQty(surplusAmount);
        productUpd.setSellQty(sellQty);
        productUpd.setValueVersion(productEnity.getValueVersion());
        productUpd.setSourceType(buyMeetcoinDto.getSourceType());
        int updateProductLine = productDao.update(productUpd);
        LOGGER.info("PayServiceImpl-------productDao.update------>" + updateProductLine);
        if (updateProductLine < 1) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新商品数量失败!");
        }

        UserAccountEnity userAccount = userAccountDao.selectByUserId(buyMeetcoinDto.getUserId());
        LOGGER.info("PayServiceImpl-------productEnity.getAmount()------>" + productEnity.getAmount());
        int totalAmount = 0;
        if (userAccount == null) {
            totalAmount = productEnity.getAmount();
        } else {
            totalAmount = userAccount.getTotalAmount() + productEnity.getAmount();
        }

        // 4、写用户资金账户流水表
        UserAccountDetailEnity userAccountDetailEnity = new UserAccountDetailEnity();
        userAccountDetailEnity.setOrderNo(OrderNoUtils.generateUniqueId());
        userAccountDetailEnity.setUserId(buyMeetcoinDto.getUserId());
        userAccountDetailEnity.setProductId(buyMeetcoinDto.getProductId());
        userAccountDetailEnity.setAmount(productEnity.getAmount());
        userAccountDetailEnity.setTotalAmount(totalAmount);
        userAccountDetailEnity.setStatus(PayStatusEnum.WAIT_PAY.getValue());
        userAccountDetailEnity.setPayType(buyMeetcoinDto.getPayType());
        userAccountDetailEnity.setCash(productEnity.getCash());
        userAccountDetailEnity.setAmountType(0);
        userAccountDetailEnity.setSourceType(buyMeetcoinDto.getSourceType());
        userAccountDetailEnity.setRemark(buyMeetcoinDto.getRemark());
        userAccountDetailEnity.setCreateTime(new Date());
        userAccountDetailEnity.setUpdateTime(new Date());

        // 5、根据支付类型选择对应的支付方式
        // 微信支付
        if (PayTypeEnum.WEIXIN.getValue().equals(buyMeetcoinDto.getPayType())) {
            WeiXinPrePay weiXinPrePay = sealWeixinPerPay(weixinAppId, weixinMchId, productEnity.getName(),
                    buyMeetcoinDto.getRemark(), userAccountDetailEnity.getOrderNo(), productEnity.getCash(),
                    new Date(), orderPeriod, WeiXinTradeTypeEnum.APP, productEnity.getId() + "", "",
                    buyMeetcoinDto.getOrderIp());
            String prePayXml = WeiXinPayUtils.getPrePayXml(weiXinPrePay, weixinPartnerKey);
            LOGGER.info("PayServiceImpl-------prePayXml------>" + prePayXml);
            Map<String, Object> prePayRequest = WeiXinPayUtils.httpXmlRequest(weixinPrepayUrl, "POST", prePayXml);
            LOGGER.info("PayServiceImpl-------prePayRequest------>" + JsonUtil.getJsonString(prePayRequest));
            if (WeixinTradeStateEnum.SUCCESS.name().equals(prePayRequest.get("return_code"))
                    && WeixinTradeStateEnum.SUCCESS.name().equals(prePayRequest.get("result_code"))) {
                String weiXinPrePaySign = WeiXinPayUtils.geWeiXintPrePaySign(weixinAppId, weixinMchId,
                        weiXinPrePay.getDeviceInfo(), WeiXinTradeTypeEnum.APP.name(), prePayRequest, weixinPartnerKey);
                LOGGER.info("PayServiceImpl-------weiXinPrePaySign------>" + weiXinPrePaySign);
                // 验证签名是否正确
                if (prePayRequest.get("sign").equals(weiXinPrePaySign)) {
                    // 保存用户资金账户流水信息
                    userAccountDetailEnity.setPrePayMsg(JsonUtil.getJsonString(prePayRequest));
                    int insertAccountDetailLine = userAccountDetailDao.insert(userAccountDetailEnity);
                    LOGGER.info("PayServiceImpl-------userAccountDetailDao.insert------>" + insertAccountDetailLine);
                    if (insertAccountDetailLine < 1) {
                        throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户资金账户流水失败!");
                    }
                    String prepayId = String.valueOf(prePayRequest.get("prepay_id"));
                    resultVo.setAppId(weixinAppId);
                    resultVo.setPartnerId(weixinMchId);
                    resultVo.setPrepayId(prepayId);
                    resultVo.setNonceStr(StringUtil.get32UUID());
                    resultVo.setTimeStamp(Long.toString(System.currentTimeMillis() / 1000));
                    resultVo.setPackageValue("Sign=WXPay");
                    resultVo.setSign(WeiXinPayUtils.getAppSign(resultVo, weixinPartnerKey));
                    LOGGER.info("PayServiceImpl-------resultVo------>" + JsonUtil.getJsonString(resultVo));

                } else {
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "微信返回结果签名异常!");
                }
            } else {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "请求微信异常!");
            }
            // 支付宝支付 https://docs.open.alipay.com/204/105465/
        } else if (PayTypeEnum.ALIPAY.getValue().equals(buyMeetcoinDto.getPayType())) {
            AlipayClient alipayClient = new DefaultAlipayClient(alipayGatewayUrl, alipayAppId, alipayPrivateKey,
                    "json", "utf-8", alipayPublicKey, "RSA2");
            // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            // SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody(productEnity.getName());
            model.setSubject(productEnity.getName());
            model.setOutTradeNo(userAccountDetailEnity.getOrderNo());
            model.setTotalAmount(productEnity.getCash().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
            model.setTimeoutExpress(orderPeriod + "m");
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setBizModel(model);
            // 异步回调地址(后台)
            request.setNotifyUrl(alipayNotifyUrl);
            // 同步回调地址（APP）
            request.setReturnUrl(null);
//            request.setBizContent(JsonUtil.getJsonString(model));
            LOGGER.info("PayServiceImpl-------request------>" + JsonUtil.getJsonString(request));
            try {
                // 这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                LOGGER.info("PayServiceImpl-------AlipayTradeAppPayResponse------>" + JsonUtil.getJsonString(response));
                // 保存用户资金账户流水信息
                userAccountDetailEnity.setPrePayMsg(JsonUtil.getJsonString(response));
                int insertAccountDetailLine = userAccountDetailDao.insert(userAccountDetailEnity);
                LOGGER.info("PayServiceImpl-------userAccountDetailDao.insert------>" + insertAccountDetailLine);
                if (insertAccountDetailLine < 1) {
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户资金账户流水失败!");
                }
                resultVo.setAlipayStr(response.getBody());
            } catch (AlipayApiException e) {
                e.printStackTrace();
                throw new ResponseCodeAwareException(ResponseCode.ERROR, e.getMessage());
            }
        } else if (PayTypeEnum.IOS.getValue().equals(buyMeetcoinDto.getPayType())) {
            // 3、写用户资金账户表
            LOGGER.info("PayServiceImpl-------iosPay------>");
            if (userAccount == null) {
                UserAccountEnity userSaveAccountEnity = new UserAccountEnity();
                userSaveAccountEnity.setUserId(buyMeetcoinDto.getUserId());
                userSaveAccountEnity.setTotalAmount(productEnity.getAmount());
                userSaveAccountEnity.setExpendAmount(0);
                userSaveAccountEnity.setTotalIncome(BigDecimal.ZERO);
                userSaveAccountEnity.setValueVersion(1L);
                userSaveAccountEnity.setCreateTime(new Date());
                userSaveAccountEnity.setUpdateTime(new Date());
                int userSaveAccountLine = userAccountDao.insert(userSaveAccountEnity);
                LOGGER.info("PayServiceImpl-------userAccountDao.insert------>" + userSaveAccountLine);
                if (userSaveAccountLine < 1) {
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户账户记录失败!");
                }
            } else {
                LOGGER.info("PayServiceImpl-------userAccount.getTotalAmount()------>" + userAccount.getTotalAmount());
                UserAccountEnity userUpdAccountEnity = new UserAccountEnity();
                userUpdAccountEnity.setId(userAccount.getId());
                userUpdAccountEnity.setUserId(buyMeetcoinDto.getUserId());
                userUpdAccountEnity.setTotalAmount(userAccount.getTotalAmount() + productEnity.getAmount());
                userUpdAccountEnity.setValueVersion(userAccount.getValueVersion());
                int userUpdAccountLine = userAccountDao.update(userUpdAccountEnity);
                LOGGER.info("PayServiceImpl-------userAccountDao.update------>" + userUpdAccountLine);
                if (userUpdAccountLine < 1) {
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新用户账户失败!");
                }
            }
            // 保存用户资金账户流水信息
            userAccountDetailEnity.setStatus(PayStatusEnum.PAY.getValue());
            int insertAccountDetailLine = userAccountDetailDao.insert(userAccountDetailEnity);
            LOGGER.info("PayServiceImpl-------userAccountDetailDao.insert------>" + insertAccountDetailLine);
            if (insertAccountDetailLine < 1) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户资金账户流水失败!");
            }

        } else {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "支付方式错误!");
        }
        return resultVo;
    }

    /**
     * 所有的商品
     */
    @Override
    public List<ProductVo> allProduct(Integer sourceType) {
        ProductEnity enity = new ProductEnity();
        enity.setStatus(JianBaEnum.DataStatusEnum.UP.getValue());
        enity.setSourceType(sourceType);
        List<ProductEnity> allProductList = productDao.select(enity);
        List<ProductVo> resulList = new ArrayList<ProductVo>();
        if (CollectionUtils.isNotEmpty(allProductList)) {
            List<ProductEnity> sortList = allProductList.stream().sorted(Comparator.comparing(ProductEnity::getAmount))
                    .collect(Collectors.toList());
            sortList.forEach(model -> {
                ProductVo resultVo = new ProductVo();
                BeanUtils.copyProperties(model, resultVo);
                resulList.add(resultVo);
            });

        }
        return resulList;
    }

    /**
     * 所有的礼品
     */
    @Override
    public List<GiftVo> allGift() {
        GiftEnity enity = new GiftEnity();
        enity.setStatus(JianBaEnum.DataStatusEnum.UP.getValue());
        List<GiftEnity> allGiftList = giftDao.select(enity);

        List<GiftVo> resulList = new ArrayList<GiftVo>();
        if (CollectionUtils.isNotEmpty(allGiftList)) {
            List<GiftEnity> sortList = allGiftList.stream().sorted(Comparator.comparing(GiftEnity::getAmount))
                    .collect(Collectors.toList());
            sortList.forEach(model -> {
                GiftVo resultVo = new GiftVo();
                BeanUtils.copyProperties(model, resultVo);
                resulList.add(resultVo);
            });

        }
        return resulList;
    }

    private WeiXinPrePay sealWeixinPerPay(String appId, String mchId, String productName, String remark,
            String bankOrderNo, BigDecimal orderPrice, Date orderTime, Integer orderPeriod,
            WeiXinTradeTypeEnum weiXinTradeTypeEnum, String productId, String openId, String orderIp) {
        WeiXinPrePay weiXinPrePay = new WeiXinPrePay();

        weiXinPrePay.setAppid(appId);
        weiXinPrePay.setMchId(mchId);
        weiXinPrePay.setBody(productName);// 商品描述
        weiXinPrePay.setAttach(remark);// 支付备注
        weiXinPrePay.setOutTradeNo(bankOrderNo);// 银行订单号

        Integer totalFee = orderPrice.multiply(BigDecimal.valueOf(100d)).intValue();
        weiXinPrePay.setTotalFee(totalFee);// 订单金额
        weiXinPrePay.setTimeStart(DateUtil.format(orderTime, "yyyyMMddHHmmss"));// 订单开始时间
        weiXinPrePay.setTimeExpire(DateUtil.format(DateUtil.addMinute(orderTime, orderPeriod), "yyyyMMddHHmmss"));// 订单到期时间
        weiXinPrePay.setNotifyUrl(weixinNotifyUrl);// 通知地址
        weiXinPrePay.setTradeType(weiXinTradeTypeEnum);// 交易类型
        weiXinPrePay.setProductId(productId);// 商品ID
        weiXinPrePay.setOpenid(openId);// 用户标识
        weiXinPrePay.setSpbillCreateIp(orderIp);// 下单IP

        return weiXinPrePay;
    }

    @Override
    public String notifyPay(String payWayCode, HttpServletRequest httpServletRequest) throws Exception {
        String printStr = "";
        Map<String, String> notifyMap = new HashMap<String, String>();
        String orderNo = null;
        String totalAmount = null;
        if (PayWayEnum.WEIXIN.name().equals(payWayCode)) {
            InputStream inputStream = httpServletRequest.getInputStream();// 从request中取得输入流
            notifyMap = WeiXinPayUtils.parseXml(inputStream);
            orderNo = notifyMap.get("out_trade_no");

        } else if (PayWayEnum.ALIPAY.name().equals(payWayCode)) {
            Map requestParams = httpServletRequest.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                // 乱码解决，这段代码在出现乱码时使用。
//                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                LOGGER.info(name + "--------------------->" + valueStr);
                notifyMap.put(name, valueStr);
            }

            LOGGER.info("notifyMap ------------------->" + JsonUtil.getJsonString(notifyMap));
            LOGGER.info("alipayPublicKey ------------------->" + alipayPublicKey);
            // 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
            boolean flag = AlipaySignature.rsaCheckV1(notifyMap, alipayPublicKey, "utf-8", "RSA2");
            // 验证成功
            if (flag) {
                // 实际验证过程建议商户务必添加以下校验：
                // 1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
                // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
                // 3、校验通知中的seller_id(支付宝用户号)（或者seller_email(支付宝账号))
                // 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
                // 4、验证app_id是否为该商户本身。

                orderNo = notifyMap.get("out_trade_no");// 获取商户之前传给支付宝的订单号（商户系统的唯一订单号）
                String sellerEmail = notifyMap.get("seller_email");// 卖家支付宝用户号
                totalAmount = notifyMap.get("total_amount");// 订单金额:本次交易支付的订单金额，单位为人民币（元）
                String appId = notifyMap.get("app_id");
                if (!alipaySellerEmail.equals(sellerEmail)) {
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "商家账号异常！");
                }
                if (!alipayAppId.equals(appId)) {
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "商家appId异常！");
                }
            } else {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "支付宝签名失败!");
            }
        }
        LOGGER.info("PayServiceImpl------notifyMap------->", JsonUtil.getJsonString(notifyMap));
        LOGGER.info("PayServiceImpl------notifyPay------->订单号{}", orderNo);
        // 根据银行订单号获取支付信息
        UserAccountDetailEnity userAccountDetail = userAccountDetailDao.selectByOrderNo(orderNo);
        if (userAccountDetail == null) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "非法订单,订单不存在!");
        }

        if (PayStatusEnum.PAY.getValue().equals(userAccountDetail.getStatus())) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "订单为成功状态!");
        }
        if (PayStatusEnum.EXPIRE_PAY.getValue().equals(userAccountDetail.getStatus())) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "订单已过期!");
        }
        // 微信回调处理
        if (PayWayEnum.WEIXIN.name().equals(payWayCode)) {
            LOGGER.info("PayServiceImpl-----payWayCode----notifyMap------>" + JsonUtil.getJsonString(notifyMap));
            String sign = notifyMap.remove("sign");
            if (WeiXinPayUtils.notifySign(notifyMap, sign, weixinPartnerKey)) {// 根据配置信息验证签名
                LOGGER.info("PayServiceImpl-------result_code------>" + notifyMap.get("result_code").toString());
                if (WeixinTradeStateEnum.SUCCESS.name().equalsIgnoreCase(notifyMap.get("result_code").toString())) {
                    notifyMap.put("sign", sign);
                    // 对数据库的操作
                    UserAccountDetailEnity enity = new UserAccountDetailEnity();
                    enity.setStatus(PayStatusEnum.PAY.getValue());
                    enity.setPayMsg(JsonUtil.getJsonString(notifyMap));
                    enity.setOrderNo(orderNo);
                    enity.setId(userAccountDetail.getId());
                    int line = userAccountDetailDao.update(enity);
                    LOGGER.info("PayServiceImpl-------userAccountDetailDao.update------>" + line);
                    // 告诉微信服务器，我收到信息了，不要在调用回调action了
                    if (line < 1) {
                        printStr = WeiXinPayUtils.setXML(Constants.FAIL, "update bussiness outTrade fail");
                        LOGGER.info("PayServiceImpl-------userAccountDetailDao.update------>"
                                + JsonUtil.getJsonString(enity));
                        throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新订单状态失败！");
                    }
                }
            } else {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "微信签名失败!");
            }

        } else if (PayWayEnum.ALIPAY.name().equals(payWayCode)) {
            // https://docs.open.alipay.com/204/105301
            // https://docs.open.alipay.com/54/106370/
            LOGGER.info("PayServiceImpl-------trade_status------>" + notifyMap.get("trade_status").toString());
            if ("TRADE_SUCCESS".equals(notifyMap.get("trade_status").toString())) {
                LOGGER.info("PayServiceImpl-------totalAmount------>" + totalAmount);
                LOGGER.info("PayServiceImpl-------cash------>"
                        + userAccountDetail.getCash().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
                if (!totalAmount.equals(userAccountDetail.getCash().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString())) {
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "支付金额异常!");
                }
                UserAccountDetailEnity enity = new UserAccountDetailEnity();
                enity.setStatus(PayStatusEnum.PAY.getValue());
                enity.setPayMsg(JsonUtil.getJsonString(notifyMap));
                enity.setOrderNo(orderNo);
                enity.setId(userAccountDetail.getId());
                int line = userAccountDetailDao.update(enity);
                LOGGER.info("PayServiceImpl-------userAccountDetailDao.update------>" + line);

                // 告诉服务器，我收到信息了，不要在调用回调action了
                if (line < 1) {
                    printStr = "fail";
                    LOGGER.info("PayServiceImpl-------userAccountDetailDao.update------>"
                            + JsonUtil.getJsonString(enity));
                    throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新订单状态失败！");
                }
            }

        } else {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "错误的支付方式!");
        }

        // 更新用户金币数量
        UserAccountEnity userAccount = userAccountDao.selectByUserId(userAccountDetail.getUserId());
        if (userAccount == null) {
            UserAccountEnity userSaveAccountEnity = new UserAccountEnity();
            userSaveAccountEnity.setUserId(userAccountDetail.getUserId());
            userSaveAccountEnity.setTotalAmount(userAccountDetail.getAmount());
            userSaveAccountEnity.setExpendAmount(0);
            userSaveAccountEnity.setTotalIncome(BigDecimal.ZERO);
            userSaveAccountEnity.setValueVersion(1L);
            userSaveAccountEnity.setCreateTime(new Date());
            userSaveAccountEnity.setUpdateTime(new Date());
            int userSaveAccountLine = userAccountDao.insert(userSaveAccountEnity);
            LOGGER.info("PayServiceImpl-------userAccountDao.insert------>" + userSaveAccountLine);
            if (userSaveAccountLine < 1) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户账户记录失败!");
            }

        } else {
            LOGGER.info("PayServiceImpl-------userAccount.getTotalAmount()------>" + userAccount.getTotalAmount());
            UserAccountEnity userUpdAccountEnity = new UserAccountEnity();
            userUpdAccountEnity.setId(userAccount.getId());
            userUpdAccountEnity.setUserId(userAccountDetail.getUserId());
            userUpdAccountEnity.setTotalAmount(userAccount.getTotalAmount() + userAccountDetail.getAmount());
            userUpdAccountEnity.setValueVersion(userAccount.getValueVersion());
            int userUpdAccountLine = userAccountDao.update(userUpdAccountEnity);
            LOGGER.info("PayServiceImpl-------userAccountDao.update------>" + userUpdAccountLine);
            if (userUpdAccountLine < 1) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新用户账户失败!");
            }
        }

        if (PayWayEnum.WEIXIN.name().equals(payWayCode)) {
            printStr = WeiXinPayUtils.setXML(Constants.SUCCESS, "OK");
        } else if (PayWayEnum.ALIPAY.name().equals(payWayCode)) {
            printStr = "success";
        } else {
            printStr = "fail";
        }

        return printStr;

    }

    @Override
    public JSONObject applePay(ApplePayDto applePayDto) {
        String responseResult = null;
        try {
            HttpClientBase hcb = new HttpClientBase();
            Map<String, String> data = new HashMap<String, String>();
            data.put("receipt-data", applePayDto.getReceiptData());
            responseResult = hcb.doPost(JsonUtil.getJsonString(data), applePayVerifyReceiptUrl);
            LOGGER.info("------applePay----" + responseResult);
            if (StringUtils.isBlank(responseResult)) {
                LOGGER.info("------applePay--返回值为空--");
            }
        } catch (Exception e) {
            LOGGER.info("------applePay接口异常----" + e);
        }

        JSONObject object = JSONObject.parseObject(responseResult);
        return object;
    }

    @Override
    public Object orderIsPay(OrderIsPayDto orderIsPayDto) throws AlipayApiException {
        // 微信支付
        Object object = null;
        if (PayTypeEnum.WEIXIN.getValue().equals(orderIsPayDto.getPayType())) {
            WXOrderQueryDto wXOrderQueryDto = new WXOrderQueryDto(weixinAppId, weixinMchId, orderIsPayDto.getOrderNo(),
                    StringUtil.get32UUID());

            String orderQueryXml = WeiXinPayUtils.getOrderQueryXml(wXOrderQueryDto, weixinPartnerKey);

            Map<String, Object> orderQueryRequest = WeiXinPayUtils.httpXmlRequest(
                    "https://api.mch.weixin.qq.com/pay/orderquery", "POST", orderQueryXml);

            if (orderQueryRequest.get("result_code") != null
                    && "SUCCESS".equalsIgnoreCase(orderQueryRequest.get("result_code").toString())) {
                object = orderQueryRequest;
            } else {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "查询失败!");
            }
        } else if (PayTypeEnum.ALIPAY.getValue().equals(orderIsPayDto.getPayType())) {

            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayAppId,
                    alipayPrivateKey, "json", "GBK", alipayPublicKey, "RSA2");
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{\"out_trade_no\":" + orderIsPayDto.getOrderNo() + "}");
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                object = JSONObject.parseObject(response.getBody());
            } else {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "查询失败!");
            }
        }
        return object;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrder(String orderNo) throws Exception {
        // 根据银行订单号获取支付信息
        UserAccountDetailEnity userAccountDetail = userAccountDetailDao.selectByOrderNo(orderNo);
        if (userAccountDetail == null) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "非法订单,订单不存在!");
        }

        if (PayStatusEnum.PAY.getValue().equals(userAccountDetail.getStatus())) {
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "订单为成功状态!");
        }
        // 对数据库的操作
        UserAccountDetailEnity enity = new UserAccountDetailEnity();
        enity.setStatus(PayStatusEnum.PAY.getValue());
        enity.setOrderNo(orderNo);
        enity.setId(userAccountDetail.getId());
        int line = userAccountDetailDao.update(enity);
        LOGGER.info("PayServiceImpl-------userAccountDetailDao.update------>" + line);
        if (line < 1) {
            LOGGER.info("PayServiceImpl-------userAccountDetailDao.update------>" + JsonUtil.getJsonString(enity));
            throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新订单状态失败！");
        }
        // 更新用户金币数量
        UserAccountEnity userAccount = userAccountDao.selectByUserId(userAccountDetail.getUserId());
        if (userAccount == null) {
            UserAccountEnity userSaveAccountEnity = new UserAccountEnity();
            userSaveAccountEnity.setUserId(userAccountDetail.getUserId());
            userSaveAccountEnity.setTotalAmount(userAccountDetail.getAmount());
            userSaveAccountEnity.setExpendAmount(0);
            userSaveAccountEnity.setTotalIncome(BigDecimal.ZERO);
            userSaveAccountEnity.setValueVersion(1L);
            userSaveAccountEnity.setCreateTime(new Date());
            userSaveAccountEnity.setUpdateTime(new Date());
            int userSaveAccountLine = userAccountDao.insert(userSaveAccountEnity);
            LOGGER.info("PayServiceImpl-------userAccountDao.insert------>" + userSaveAccountLine);
            if (userSaveAccountLine < 1) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "保存用户账户记录失败!");
            }

        } else {
            LOGGER.info("PayServiceImpl-------userAccount.getTotalAmount()------>" + userAccount.getTotalAmount());
            UserAccountEnity userUpdAccountEnity = new UserAccountEnity();
            userUpdAccountEnity.setId(userAccount.getId());
            userUpdAccountEnity.setUserId(userAccountDetail.getUserId());
            userUpdAccountEnity.setTotalAmount(userAccount.getTotalAmount() + userAccountDetail.getAmount());
            userUpdAccountEnity.setValueVersion(userAccount.getValueVersion());
            int userUpdAccountLine = userAccountDao.update(userUpdAccountEnity);
            LOGGER.info("PayServiceImpl-------userAccountDao.update------>" + userUpdAccountLine);
            if (userUpdAccountLine < 1) {
                throw new ResponseCodeAwareException(ResponseCode.ERROR, "更新用户账户失败!");
            }
        }
    }
}
